package com.offcn.proxy;

import com.offcn.config.RpcServerConfig;
import com.offcn.dto.RpcRequestParams;
import com.offcn.service.HelloService;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

public class HelloServiceProxy implements HelloService {
    /**
     * 计算加法
     *
     * @param one 参数一
     * @param two 参数二
     * @return 返回结果
     */
    @Override
    public int add(int one, int two) {
        try {
            Socket socket = new Socket(RpcServerConfig.ADDRESS, RpcServerConfig.PORT);
            //创建请求参数封装对象
            RpcRequestParams rpcRequestParams = new RpcRequestParams(one, two);
            //创建序列化生成器
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
            //把请求参数对象序列化发送给服务器端
            objectOutputStream.writeObject(rpcRequestParams);
            //接收服务器响应，创建反序列化器
            ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());
            Object response = objectInputStream.readObject();
            //判断响应类型是否是整数
            if(response instanceof Integer){
                return (Integer) response;
            }else {
                throw new RuntimeException();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

       return 0;
    }
}
